package com.example.basic.filter;

import com.example.basic.base.Constants;
import com.example.basic.core.URLConstants;
import com.example.basic.utils.JwtUtil;
import com.example.basic.utils.StringUtils;
import com.example.basic.exception.TokenValidationException;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * token过滤器
 *
 * @author lpp
 * @date 2019/11/19
 */
@Order(0)
@WebFilter(filterName = "TokenParseFilter", urlPatterns = "/*")
public class TokenParseFilter extends OncePerRequestFilter {
    public static final String LOGIN_TOKEN = "login_token_";
    public static final String TOKEN_PREFIX = "Bearer";

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 需要排除的页面
     */
    private String[] excludedUrlArray = {
            URLConstants.API_LOGIN_URL,URLConstants.webSocket
    };


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        MutableHttpServletRequest mutableRequest = new MutableHttpServletRequest(request);
        String uri = mutableRequest.getRequestURI();
        // 静态资源要跳过验证
        if (StringUtils.isNotBlank(uri)) {
            String[] uriParts = uri.split("\\?");

            if(uriParts[0].contains(Constants.DOT)){
                filterChain.doFilter(mutableRequest, response);
                return;
            }

            if (uri.contains(URLConstants.API_LOGIN_URL)) {
                filterChain.doFilter(mutableRequest, response);
                return;
            }
            if (uri.contains(URLConstants.webSocket)) {
                filterChain.doFilter(mutableRequest, response);
                return;
            }

            if (uri.contains(URLConstants.WX_LOGIN_URL)) {
                filterChain.doFilter(mutableRequest, response);
                return;
            }

            if (uri.contains(URLConstants.WX_GET_PHONE_URL)) {
                filterChain.doFilter(mutableRequest, response);
                return;
            }

            if (uri.contains(URLConstants.WEB_SOCKET)) {
                filterChain.doFilter(mutableRequest, response);
                return;
            }

            if (uri.contains(URLConstants.SWAGGER_HTML) || uri.contains(URLConstants.SWAGGER_DOC)) {
                filterChain.doFilter(mutableRequest, response);
                return;
            }

            if (uri.contains(URLConstants.demo) || uri.contains(URLConstants.transTask) || uri.contains(URLConstants.common)) {
                filterChain.doFilter(mutableRequest, response);
                return;
            }
        }

        String token = request.getHeader(JwtUtil.HEADER_STRING);
        Map<String, Object> stringObjectMap = JwtUtil.validateToken(token);

        //在request中添加当前机构，用户的id
        request.setAttribute("userCode", stringObjectMap.get("userCode"));
        request.setAttribute("userName", stringObjectMap.get("userName"));
        request.setAttribute("loginName", stringObjectMap.get("loginName"));
        String s = (String) redisTemplate.opsForHash().get(LOGIN_TOKEN + stringObjectMap.get("loginName"), stringObjectMap.get("loginName"));
        String replace = s.replace(TOKEN_PREFIX, "");
        if (!replace.equals(token.replace(TOKEN_PREFIX, ""))) {
            //应前端要求 返回这个
            throw new TokenValidationException("Missing token");
        }
        filterChain.doFilter(mutableRequest, response);
    }
}
